﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Verse.AI;
using Verse;

namespace RimZombieGirl {
    public class JobDriver_EnterTransformationCoffin : JobDriver
    {
        public override bool TryMakePreToilReservations(bool errorOnFailed)
        {
            return this.pawn.Reserve(this.job.targetA, this.job, 1, -1, null, errorOnFailed, false);
        }

        protected override IEnumerable<Toil> MakeNewToils()
        {
            this.FailOnDespawnedOrNull(TargetIndex.A);
            yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell, false);
            Toil toil = Toils_General.Wait(500, TargetIndex.None);
            toil.FailOnCannotTouch(TargetIndex.A, PathEndMode.InteractionCell);
            toil.WithProgressBarToilDelay(TargetIndex.A, false, -0.5f);
            yield return toil;
            Toil enter = ToilMaker.MakeToil("MakeNewToils");
            enter.initAction = delegate ()
            {
                Pawn actor = enter.actor;
                Building_TransformationCoffin pod = (Building_TransformationCoffin)actor.CurJob.targetA.Thing;
                Action action = delegate ()
                {
                    bool flag = actor.DeSpawnOrDeselect(DestroyMode.Vanish);
                    if (pod.TryAcceptThing(actor, true) && flag)
                    {
                        Find.Selector.Select(actor, false, false);
                    }
                    
                };
                if (pod.def.building.isPlayerEjectable)
                {
                    action();
                    return;
                }
                if (this.Map.mapPawns.FreeColonistsSpawnedOrInPlayerEjectablePodsCount <= 1)
                {
                    Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("CoffinWarning".Translate(actor.Named("PAWN")).AdjustedFor(actor, "PAWN", true), action, false, null, WindowLayer.Dialog));
                    return;
                }
                action();
            };
            enter.defaultCompleteMode = ToilCompleteMode.Instant;
            yield return enter;
            yield break;
        }
    }
}
